package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gogf/gf/net/gtcp"
)

var NewMessageService = new(serviceMessage)

type serviceMessage struct{}

type RecvMsgAction string
const (
	RecvMsgAction_Bind RecvMsgAction = "bind"
	RecvMsgAction_ToUid RecvMsgAction = "toUid"
)

type RecvMsg struct {
	Imei   string `json:"imei"`
	ToImei   string `json:"toImei"`
	Action RecvMsgAction `json:"action"`
	Data   interface{} `json:"data"`
}

type RespMsg struct {
	Code    int `json:"code"`
	Message string `json:"message"`
	Data    interface{} `json:"data"`
}

//{"imei":"10001","action":"bind","toImei":"","data":""}
//{"imei":"10001","action":"toUid","toImei":"10002","data":"hello10002"}
//{"imei":"10002","action":"bind","toImei":"","data":""}

func (s *serviceMessage) OnMessage(conn *gtcp.Conn, message []byte) {
	// //测试：仅回显
	// err := conn.Send(append([]byte("Client say : "), message...))
	// if err != nil {
	// 	fmt.Println("conn-error", err)
	// }
	respMsg := new(RespMsg)

	recvMsg := new(RecvMsg)
	err := json.Unmarshal(message, recvMsg)
	if err != nil {
		respMsg.Code = 0
		respMsg.Message = err.Error()
	} else {
		if recvMsg.Action == RecvMsgAction_Bind {
			err = NewServerService.BindUid(conn, recvMsg.Imei)
		} else if recvMsg.Action == RecvMsgAction_ToUid {
			newMsg, err2 := json.Marshal(recvMsg)
			if err2 == nil {
				err = NewServerService.SendToUid(recvMsg.ToImei, newMsg)
			} else {
				err = err2
			}
		} else {
			err = errors.New("action error")
		}

		if err != nil {
			respMsg.Code = 0
			respMsg.Message = err.Error()
		} else {
			respMsg.Code = 1
			respMsg.Message = "success"
		}
	}

	respByte, err := json.Marshal(respMsg)
	if err != nil {
		fmt.Println("OnMessage : error", err)
	}
	err = conn.Send(respByte)
	if err != nil {
		fmt.Println("OnMessage : error", err)
	}
}
